<template>
  <div>
    <!-- <el-button @click="showDialog" type="primary" icon="el-icon-plus" style="margin-top: 20px"
      >添加</el-button
    > -->

    <el-table :data="webuserlist" border style="width: 100%; margin-top: 100px">
      <el-table-column type="index" label="ID" width="80" align="center">
      </el-table-column>
      <el-table-column prop="nickName" label="用户名称" width="280" align="center">
      </el-table-column>
      <!-- <el-table-column prop="gender" label="性别" width="280" align="center">
        <template slot-scope="{ row }">
          <span>{{row.gender == 0 ? "男" : "女"}}</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="avatarUrl" label="头像" align="center">
        <template slot-scope="{ row }">
          <img :src="row.avatarUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系方式" width="280" align="center">
      </el-table-column>
      <!-- 更改丢失 -->
      <!-- <el-table-column prop="logoUrl" label="丢失物品" align="center">
        <template slot-scope="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column> -->
      <el-table-column pro="" label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-edit" @click="showDialog(row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteu(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 
        通过给el-table属性添加标签属性data，可以将需要遍历的数组交给el-table组件
        el-table会将当前data交给每一个el-table-column组件，组件内部会自动进行v-for遍历

     -->
    <el-pagination
      style="text-align: center; margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[2, 3, 10]"
      :page-size="limit"
      layout="prev, pager, next, jumper,->,total,sizes"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      :title="userForm.openId? '修改用户' : '添加用户'"
      style="width:100%"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="userForm" :rules="rules" ref="addForm">
        <el-form-item label="用户名称" label-width="100px"  prop ="userName">
          <el-input v-model="userForm.nickName" autocomplete="off"></el-input>
        </el-form-item>
         <!-- <el-form-item label="用户性别"  prop="gender" label-width="100px" >
            <el-radio-group v-model="userForm.gender"  >
              <el-radio :label=0>男</el-radio>
              <el-radio :label=1>女</el-radio>
            </el-radio-group>
        </el-form-item> -->
        <el-form-item label="用户头像" label-width="100px" prop="avatarUrl">
            <!-- 此处的action需要填写图片上传的网络路径，记得加前缀/dev-api -->
            <!--POST /manage_system/file/upload  -->

          <el-upload
            class="avatar-uploader"
            action="https://lfcon.hxcraft.top/service_manage/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="userForm.avatarUrl" :src="userForm.avatarUrl " class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
             <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="联系方式" label-width="100px"  prop ="phone">
          <el-input v-model="userForm.phone" autocomplete="off"></el-input>
        </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="concel">取 消</el-button>
        <el-button type="primary" @click="save()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {getToken}  from "@/utils/auth";
export default {
  name: "UserList",
  data() {
    return {
      page: 1,
      limit: 10,
      total: 15,
      webuserlist: [],
      dialogFormVisible: false,
      userForm: {
        // logoUrl : 'http://1.117.57.89'+avatarUrl,
        nickName: "",
        avatarUrl: "",
        phone: "",
      },
      //校验规则
      // rules:{
      //   //当前对象中的属性名，必须跟el-form-item组件中的prop对象
      //   //属性值（object[]）就是给对应的prop的item组件使用的校验规则
      //   //数组中的每一个对象，就是一条校验规则
      //   //trigger代表校验时机，在form表单校验中，一共有三个校验时机
      //   //1.失去焦点(blur事件),2.内容改变（change）3.主动校验(通过调用API来实现)
      //   userName :[
      //     { required: true, message: '请输入用户名称', trigger: 'blur' },
      //     { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'change' }
      //   ],
      //   avatarUrl:[
      //      { required: true, message: '请添加物品图片', trigger: 'blur' },
      //   ]
      // },
    };
  },
  mounted() {
    this.getUserList(this.page);
  },
  methods: {
        //分页
        async getUserList(page){
            const {
                data : { total, items },
            } = await this.$API.webuserlist.getUserList(getToken(),page ? page : this.page ,this.limit)
            // const result = await this.$API.userlist.getUserList(getToken(), this.page ,this.limit)
            // console.log(result)
            this.total = total;
            if(page){
              this.page = page
            }
            // console.log(result);
            this.webuserlist = items;
        },

        //分页点击
        handleCurrentChange(value) {
        //通过当前事件，可以知道用户点击了哪个页数
        this.page = value;
        //发送请求，获取对应页面的数据
        this.getUserList(this.page);
        },

        //限制当前页面显示的数量
        handleSizeChange(value) {
        this.limit = value;
        this.getUserList(this.page);
        },

        handleAvatarSuccess(res) {
            //由于用户通过input标签选中图片后，该图片就存储于浏览器内存中
            //以下代码是将内存中的图片，生成本地链接地址，用来展示
            // this.avatarUrl = URL.createObjectURL(file.raw);
            // console.log(res.data);
            //"http://1.117.57.89/" +
            this.userForm.avatarUrl =`http://lfmini.hxcraft.top`+res.data[0].url;
        },

        beforeAvatarUpload(file) {
            const types = ['image/jpeg','image/jpg','image/png'];
            const isJPG = types.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },

        showDialog(row){
          //该函数添加属性和编辑属性都会调用
          //编辑属性的时候会传入row（当前行的数据对象）
          //通过id属性判断当前回调函数的触发来源
          // alert(row.id)
          if(row.id){
            //只有编辑才能进入该区域
            //此处是引用值传递
            //...是浅拷贝，将当前row对象中的所有属性以及他们的值复制一份到tmForm中
            this.userForm = {
              ...row
            };

          }
            this.dialogFormVisible = true
        },
        
        save(){
          //首先先校验数据的合法信
            this.$refs.addForm.validate(async(valid)  => {
            //valid代表表单的全部校验结果
            if (valid) {
              //1、收集请求所需要的数据
              //已经整理在userForm中，不需要在收集
              // alert(1)
            //   this.userForm.gender =  Number(this.userForm.gender)
              try {
                    //2.发送请求
                    
                    await this.$API.webuserlist.addOrUpdate(getToken(),this.userForm);
                    // console.log(this.userForm);
                    // alert(1)
                    //请求最新的品牌列表，由于添加功能无法知道在那一页，所以统一请求第一页
                    this.getUserList(this.page);
                    //弹窗提示
                    //3.成功之后
                    // if(row.id){
                    //   this.$message({
                    //     message:'修改成功',
                    //     type:'success'
                    //   })
                    // }
                    this.$message({
                        message:'修改成功',
                        type: 'success'
                    });
                    //将添加框隐藏
                    this.dialogFormVisible = false
                    //清空当前dialog的内容
                    this.userForm = {
                      nickName: "",
                      avatarUrl: "",
                      phone: "",

                    }
                } catch (error) {
                  //4.失败之后
                    this.$message({
                        message: '修改失败',
                        type: 'info'
                    });
                   
                } 
            } else {
               this.dialogFormVisible = false
            //this.$message.info("保存失败")
            }
          });
           
        },

        concel(){
          this.dialogFormVisible = false
          this.userForm = {
            nickName: "",
            avatarUrl: "",
            phone: "",
         }
        },

        deleteu(row) {
        // alert(row.id)
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          //点击确定之后执行的代码
          //发送请求 
          try {
            //1.发送请求
              await this.$API.webuserlist.deleteUser(getToken(),row.id);
              this.$message({
              type: 'success',
              message: '删除成功!'
            });
            //请求最新列表
            //如果当前页面还有数据就请求当前页面
            //如果删除的是当前页面的最后一个数据则请求前一个夜间
            this.getUserList(this.webuserlist.length>1? this.page:this.page-1);
          } catch (error) {
              this.$message({
              type: 'info',
              message: '删除失败'
            });
          }   
        }).catch(() => {
            this.$message({
            type: 'info',
            message: '已取消删除'
          });        
        });
      }
    }
};
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>